package com.ftp.web.spider.service.nettyserver;

import io.netty.channel.*;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.stream.ChunkedFile;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;


public class NettyFileHandler extends ChannelInboundHandlerAdapter {
    private String file_dir = "D:\\new.jpg";

    private static final String CR=System.getProperty("line.separator");



    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws IOException {
        RandomAccessFile randomAccessFile=null;
        System.out.println(msg);
        try {
            randomAccessFile=new RandomAccessFile(file_dir,"rw");
            long s=new File(file_dir).length();
            if(msg instanceof byte[]){
                randomAccessFile=new RandomAccessFile(file_dir,"rw");
                byte[] mediaByte=(byte[]) msg;
                randomAccessFile.skipBytes((int)s);
                randomAccessFile.write(mediaByte);
            }
            ctx.writeAndFlush(s);
            randomAccessFile.close();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
                randomAccessFile.close();
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
